#coding=utf-8
import logging

import sys

from wechatpy import WeChatOAuth, WeChatClient
from wechatpy.client.api import WeChatJSAPI, WeChatMedia

from worldcup.commons.CommonResult import rest, CommonResult
from worldcup.commons.JsSdk import Sign

logger = logging.getLogger('django')
reload(sys)
sys.setdefaultencoding('utf8')

APP_ID = "wx3d857b42797b5eb4"

APP_SECRET = "90364d4eec9ab9246ff64d32207b227a"


client = WeChatClient(APP_ID, APP_SECRET)
jsapi = WeChatJSAPI(client)
weChatMedia = WeChatMedia(client)

def get_ticket():
	ticket = jsapi.get_jsapi_ticket()
	return ticket


@rest
def sign(request):
	url = request.GET.get("url")
	if url is None:
		url = request.path
	# 获取ticket，自动缓存（官方文档这么说的，待测试。。。）
	ticket = jsapi.get_jsapi_ticket()
	sign = Sign(ticket, url)
	return CommonResult(0, sign.sign())


@rest
def access_token(request):
	return CommonResult(0, client.access_token)


@rest
def download(request):
	media_id = request.GET.get("media_id")
	openid = request.GET.get("openid")
	if media_id is None:
		return CommonResult(-1, "media_id为空")
	if openid is None:
		return CommonResult(-1, "openid为空")

	response = weChatMedia.download(media_id)
	with open('/home/gmj/code/img/' + openid + ".jpg", 'wb') as f:
		f.write(response.content)
		f.close()
	return CommonResult(0, "success")



